/**
 * Created by woziji00226 on 2024-12-11 15:56:31.
 */

(function () {
    SinglePlayerGame.regSaveCustomGlobalData("maxScore", Callback.New(() => {
        return EatApppleGame_Score_W26.score;
    }, this))
})()


class EatApppleGame_Score_W26 {
    public static EVENT_SCORE_CHANGE = 'EVENT_SCORE_CHANGE';

    private static _score: number = 0;

   


    public static get score() {
        return this._score;
    }

    public static set score(value: number) {
        this._score = value;
        EventUtils.happen(EatApppleGame_Score_W26, EatApppleGame_Score_W26.EVENT_SCORE_CHANGE, [this.score]);
    }


    public static get maxScore(): number {
        return SinglePlayerGame.getSaveCustomGlobalData("maxScore");
    }
}


class GUI_eatAppleGamePlay_W26 extends GUI_15003 {

    private _rows: Array<GUI_eatAppleRow_W26> = [];

    private _maxLen: number = 30;

    //ms 200次 100 毫秒 = 20秒
    private _maxCountdown: number = 2000;

    private _playing: boolean = false;

    private _tween: Tween = null;

    private _countdown: EatAppleGame_Countdown_W26 = null;

    private _activeRowIndex: number = 0;

    constructor() {
        super();
        this._countdown = new EatAppleGame_Countdown_W26(this._maxCountdown);
        this._tween = new Tween();
        this.on(GameUI.EVENT_CLOSE_SYSTEM_UI, this, () => {
            this._tween.clear();
            this._tween = null;

            this.stop();
        });

        this.GameStart.visible = true;
        this.GameOver.visible = false;


        this.startButton.on(EventObject.CLICK, this, this.start);
        this.restartButton.on(EventObject.CLICK, this, this.restart);
        //this.start();

    }

    /**
     * 开启游戏
     */
    public start() {

        this.init();
        this.UI.visible = true;
        this._playing = true;

        this.GameStart.visible = false;
        this.GameOver.visible = false;

        this.visiablePanel.y = 0;

        this.activeRowIndex = 1;

        this._countdown.on(EatAppleGame_Countdown_W26.EVENT_COUNTDOWN_COMPLETED, this, this.onTimeOver);
        this._countdown.on(EatAppleGame_Countdown_W26.EVENT_CURRENT_COUNTDOWN_CHANGE, this, this.onChangeCountdown);
        EventUtils.addEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_EAT_APPLE, this.onSucessClick, this);
        EventUtils.addEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_EAT_EMPTY_APPLE, this.onFailClick, this);
        EventUtils.addEventListenerFunction(EatApppleGame_Score_W26, EatApppleGame_Score_W26.EVENT_SCORE_CHANGE, this.onScoreChange, this);
        this._countdown.start();
        this._countdown.pause();

        EatApppleGame_Score_W26.score = 0;
    }

    /**
     * 停止不可以操作了
     */
    private stop() {
        this._countdown.clear();
        this._playing = false;

        for (var i = 0; i < this._rows.length; i++) {
            var row = this._rows[i];
            row.canClick = false;
        }

        this._countdown.offAll();

        EventUtils.removeEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_EAT_APPLE, this.onSucessClick, this);
        EventUtils.removeEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_EAT_EMPTY_APPLE, this.onFailClick, this);
        EventUtils.removeEventListenerFunction(EatApppleGame_Score_W26, EatApppleGame_Score_W26.EVENT_SCORE_CHANGE, this.onScoreChange, this);
    }


    public gameOver() {
        this.stop();

        if (EatApppleGame_Score_W26.score > EatApppleGame_Score_W26.maxScore) {
            //更新新的最高分数
            SinglePlayerGame.saveGlobalData(Callback.EMPTY);
        }

        this.overTextLabel.text = `呵呵！我吃掉了${EatApppleGame_Score_W26.score}个小苹果！ 亲，还得加油哦!`;
        this.overScoreTextLabel.text = `最佳 ${EatApppleGame_Score_W26.maxScore}`;

    }

    /**
     * 重启游戏
     */
    public restart() {
        this.stop();
        this.start();
    }

    /**
     * 在尾部加一行
     */
    private pushRow() {

        var row = new GUI_eatAppleRow_W26();

        if (this.lastRow == null) {
            //第一行
            row.x = 0;
            row.y = this.visiablePanel.height - row.visiableContainer.height;
            row.hideAllApple();
        }
        else {
            row.x = 0;
            row.y = this.lastRow.y - row.visiableContainer.height;
        }

        this.visiablePanel.addChild(row);
        this._rows.push(row);


        /*
        if (this._rows.length > this._maxLen) {
            var row0 = this._rows.shift();
            row0.removeSelf();
            row0.dispose();
        }
        */

    }

    /**
     * 激活下一行
     */
    private activaNextRow() {
        this.activeRowIndex += 1;
    }

    /**
     * 成功选择
     */
    private onSucessClick() {
        EatApppleGame_Score_W26.score += 1;
        GameAudio.playSE("asset/audio/se/3.mp3");
        this.pushRow();
        this.activaNextRow();
        this.roll();
        if (!this._countdown.playing) {
            this._countdown.continue();
        }
    }

    /**
     * 选错
     */
    private onFailClick() {

        if (!this._playing) {
            return;
        }

        GameAudio.playSE("asset/audio/se/1.mp3");

        EventUtils.addEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_PLAY_ANIMI_COMPLETED, this.onPlayFailAnimiCompleted, this);
        this.gameOver();
    }

    /**
     * 超时
     */
    private onTimeOver() {
        GameAudio.playSE("asset/audio/se/2.mp3")
        for (var i = 0; i < this._rows.length; i++) {
            var row = this._rows[i];
            row.playAnimi();
        }
        this.countdownLabel.text = '时间到！';
        EventUtils.addEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_PLAY_ANIMI_COMPLETED, this.onPlayFailAnimiCompleted, this);
        this.gameOver();
    }

    /**
     * 当倒计时改变时
     */
    private onChangeCountdown(countdown: number) {
        var text = Math.floor(countdown).toString().padStart(4, '0');
        text = text.slice(0, 2) + `'` + text.slice(2) + `''`;
        this.countdownLabel.text = text;
    }

    /**
     * 分数改变
     * @param score 
     */
    private onScoreChange(score: number) {
        this.scoreLabel.text = score.toString();
    }

    /**
     * 滚动一下
     */
    private roll() {

        if (!this._playing) {
            return;
        }

        this._tween.complete();
        this._tween.to(this.visiablePanel, { y: this.visiablePanel.y + GameSprite_eatApple_W26.RootHeight }, 100, Ease.linearIn, Callback.EMPTY, 0, false);
    }

    /** 
     * 播放失败动画结束
     */
    private onPlayFailAnimiCompleted() {
        this.GameOver.visible = true;
        EventUtils.removeEventListenerFunction(GameSprite_eatApple_W26, GameSprite_eatApple_W26.EVENT_PLAY_ANIMI_COMPLETED, this.onPlayFailAnimiCompleted, this);
    }

    /**
     * 初始化
     */
    private init() {
        this.clear();
        //创建
        for (var i = 0; i < Math.floor(this._maxLen / 2); i++) {
            this.pushRow();
        }

        this._rows[1].canClick = true;
    }


    /**
     * 清理所有行
     */
    private clear() {
        var row = this._rows.pop();
        while (row != null) {
            row.removeSelf();
            row.dispose();
            row = this._rows.pop();
        }
        this._rows.length = 0;
    }

    /**
     * 获取上一行
     * @return [GUI_eatAppleRow_W26] 
     */
    private get lastRow(): GUI_eatAppleRow_W26 {
        var len = this._rows.length;
        if (len == 0) {
            return null;
        }
        return this._rows[this._rows.length - 1] as GUI_eatAppleRow_W26;
    }


    private get visiablePanel() {
        return this.panel;
    }

    private get activeRowIndex() {
        return this._activeRowIndex;
    }

    private set activeRowIndex(index: number) {
        if (this._rows[this._activeRowIndex]) {
            this._rows[this._activeRowIndex].canClick = false;
        }
        this._activeRowIndex = index;
        this._rows[this._activeRowIndex].canClick = true;
    }

}